package pyip.lib.mixtool.temp;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class CloneUtil {

    /**
     * 深度克隆
     * @param obj
     * @return
     * @throws Exception
     */
    public static Object cloneObject(Object obj) throws Exception {
        ByteArrayOutputStream outByte = null;
        ObjectOutputStream out = null;
        ByteArrayInputStream inByte = null;
        ObjectInputStream in = null;
        try {
            outByte = new ByteArrayOutputStream();
            out = new ObjectOutputStream(outByte);
            out.writeObject(obj);

            inByte = new ByteArrayInputStream(outByte.toByteArray());
            in = new ObjectInputStream(inByte);
            Object robj = in.readObject();
            return robj;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (inByte != null) {
                    inByte.close();
                }
                if (out != null) {
                    out.close();
                }
                if (outByte != null) {
                    outByte.close();
                }
            } catch (IOException e) {
                // TODO log
                e.printStackTrace();
            }
        }
    }

}
